import pandas as pd
import quantecon as qe
OMP: Info #276: omp_set_nested routine deprecated, please use omp_set_max_active_levels instead.
fp = "../data/stochastic_matrix_coffee_price-regime-R-8.csv"
df = pd.read_csv(fp, usecols = ["L", "M", "H"])
col_order = ["L", "M", "H"]
df = df[col_order]
sm = df.values
sm
array([[0.867, 0.133, 0.   ],
       [0.2  , 0.667, 0.133],
       [0.   , 0.188, 0.812]])
from quantecon import MarkovChain

mc = qe.MarkovChain(sm, ("L", "M", "H"))
mc.is_irreducible
True
mc.communication_classes
[array(['L', 'M', 'H'], dtype='<U1')]
mc.is_aperiodic
True
mc.stationary_distributions
array([[0.46828491, 0.31140946, 0.22030563]])
import plotly.express as px

fig = px.imshow(sm, text_auto=True,  labels=dict(x="Previous Month Price", y="Current Month Price"),
                x=['Low', 'Medium', 'High'],
                y=['Low', 'Medium', 'High'])
fig.update_layout(
    title={
        'text': "Stochastic Matrix for Region 8",
        'y':.95,
        'x':0.5,
        'xanchor': 'center',
        'yanchor': 'top'})

fig.show()
d = mc.stationary_distributions.flatten().tolist()
stationary_dist = {"Low": d[0], "Medium": d[1], "High": d[2]}
dfp = pd.DataFrame.from_dict(stationary_dist, orient='index').round(3)
dfp = dfp.reset_index()
dfp.col
Probablity
Low 0.468
Medium 0.311
High 0.220
import numpy as np
# If you are interested in prices two months ahead, raise the stochastic matrix to the power 2
two_step_prob = np.matmul(mc.stationary_distributions, np.matmul(sm, sm))
[0.4682849065298344, 0.31140946284233995, 0.2203056306278256]
two_step_prob
array([[0.46828491, 0.31140946, 0.22030563]])